package com.jilefojing.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jilefojing.beans.data.enums.ResponseEnum;
import com.jilefojing.beans.data.response.base.ResponseData;
import com.jilefojing.beans.data.web.response.BookChapterData;
import com.jilefojing.beans.enums.ItemTypeEnumForSource;
import com.jilefojing.beans.enums.StatusEnumForPublish;
import com.jilefojing.beans.exception.UserContextException;
import com.jilefojing.beans.pojos.DBuddhism;
import com.jilefojing.beans.pojos.EBookChapter;
import com.jilefojing.beans.pojos.Statistics;
import com.jilefojing.beans.pojos.WriteBook;
import com.jilefojing.beans.pojos.enhanced.EnhancedDBuddhism;
import com.jilefojing.beans.pojos.enhanced.EnhancedEBookChapter;
import com.jilefojing.beans.pojos.enhanced.EnhancedWriteBook;
import com.jilefojing.beans.query.DBuddhismQuery;
import com.jilefojing.beans.query.EBookChapterQuery;
import com.jilefojing.beans.query.WriteBookQuery;
import com.jilefojing.beans.vo.Order;
import com.jilefojing.beans.vo.Pagination;
import com.jilefojing.context.beans.vo.UserContext;
import com.jilefojing.service.IDBuddhismService;
import com.jilefojing.service.IEBookChapterService;
import com.jilefojing.service.IEBookService;
import com.jilefojing.service.IStatisticsService;
import com.jilefojing.service.IWriteBookService;
import com.jilefojing.util.Detect;
import com.jilefojing.web.base.BaseWeb;
import com.jilefojing.web.convent.CommonConvent;
import com.octo.captcha.service.multitype.MultiTypeCaptchaService;

@Controller
@RequestMapping("write")
public class WriteWeb extends BaseWeb {
	@Autowired
	private IEBookService eBookService;
	@Autowired
	private IEBookChapterService eBookChapterService;
	@Autowired
	private IDBuddhismService dBuddhismService;
	@Autowired
	private IWriteBookService writeBookService;
	@Autowired
	private MultiTypeCaptchaService captchaService;
	@Autowired
	private IStatisticsService statisticsService;

	@RequestMapping("dedicate-merits-list.html")
	public String toDedicateMeritsListPage(HttpServletRequest request,
			Integer page, String nKeywords) {
		int index = 1;
		if (page != null) {
			index = page;
		}

		WriteBookQuery writeBookQuery = new WriteBookQuery();
		writeBookQuery.setLike_writeUserName(nKeywords);

		Pagination<EnhancedWriteBook> pagination = new Pagination<EnhancedWriteBook>(
				index, 20, true);
		pagination.addOrder(new Order(WriteBook.COLUMN_CREATE_TIME,
				Order.ORDER_DESC));

		pagination = writeBookService.getPagination(writeBookQuery, pagination,
				null);

		request.setAttribute("writeBooks", pagination.getItems());
		request.setAttribute("pagination", pagination);

		return "web/write/dedicate_merits_list";
	}

	@RequestMapping("dedicate-merits-list-part.html")
	public String getDedicateMeritsListPartPage(HttpServletRequest request,
			Integer page, String nKeywords) {
		int index = 1;
		if (page != null) {
			index = page;
		}

		WriteBookQuery writeBookQuery = new WriteBookQuery();
		writeBookQuery.setLike_writeUserName(nKeywords);

		Pagination<EnhancedWriteBook> pagination = new Pagination<EnhancedWriteBook>(
				index, 20, true);
		pagination.addOrder(new Order(WriteBook.COLUMN_CREATE_TIME,
				Order.ORDER_DESC));

		pagination = writeBookService.getPagination(writeBookQuery, pagination,
				null);

		request.setAttribute("writeBooks", pagination.getItems());
		request.setAttribute("pagination", pagination);

		return "web/write/dedicate_merits_list_part";
	}

	@RequestMapping("save")
	public @ResponseBody ResponseData saveWriteBook(WriteBook writeBook,
			HttpServletRequest request, String verificationCode) {
		ResponseData responseData = new ResponseData();

		Boolean isResponseCorrect = captchaService.validateResponseForID(
				request.getSession().getId(), verificationCode);
		if (!isResponseCorrect) {
			responseData.setResponseEnum(ResponseEnum.IMG_VALIDATA_ERROR);
			return responseData;
		}

		UserContext userContext = null;
		try {
			userContext = super.getUserContext();
		} catch (UserContextException e) {
			// 可忽略
		}
		try {
			writeBookService.saveForActive(writeBook, userContext);

			statisticsService.updateCount(ItemTypeEnumForSource.BOOK_CHAPTER,
					writeBook.getBookChapterId(),
					Statistics.COLUMN_COUNT_WRITE, true, 1, null);
		} catch (UserContextException e) {
			if (e.getResponse() != null) {
				responseData.setResponseEnum(e.getResponse());
			} else {
				responseData.setResponseEnum(ResponseEnum.UNKNOWN);
				responseData.setResponseMessage(e.getMessage());
			}
		}

		return responseData;
	}

	@RequestMapping("{id}.html")
	public String toWritePage(HttpServletRequest request,
			@PathVariable("id") long id) {
		EnhancedEBookChapter enhancedEBookChapter = (EnhancedEBookChapter) eBookChapterService
				.getEnhanced(id, null);

		DBuddhismQuery dBuddhismQuery = new DBuddhismQuery();
		Pagination<EnhancedDBuddhism> pagination = new Pagination<EnhancedDBuddhism>(
				1, Integer.MAX_VALUE);
		pagination.addOrder(new Order(DBuddhism.COLUMN_SORT, Order.ORDER_DESC));

		pagination = dBuddhismService.getPagination(dBuddhismQuery, pagination,
				null);
		request.setAttribute("buddhisms", pagination.getItems());

		BookChapterData chapter = CommonConvent
				.convent2EBookChapterData(enhancedEBookChapter);

		List<String> lines = this.getLinesFromChapter(chapter);

		request.setAttribute("lines", lines);
		request.setAttribute("chapter", chapter);
		return "web/write/write";
	}

	/**
	 * 获得抄写的每一行
	 * 
	 * @param chapter
	 * @return
	 */
	private List<String> getLinesFromChapter(BookChapterData chapter) {
		int lineWords = 53;

		List<String> lines = new ArrayList<String>();

		String contentText = chapter.getContentText().replaceAll("\\pZ", "");
		String[] textLines = contentText
				.split("(。”)+|(？”)+|(！”)+|(\\.{3,}”)+|[。？！]+|\\.{3,}");
		for (String _TextLine : textLines) {
			if (_TextLine.length() < 55) {
				lines.add(_TextLine);
			} else {
				int curTextLineLength = _TextLine.length();
				int hasLineIndex = curTextLineLength / lineWords
						+ (curTextLineLength % lineWords > 0 ? 1 : 0);
				for (int i = 0; i < hasLineIndex; i++) {
					if (i == hasLineIndex - 1) {
						lines.add(_TextLine.substring(i * lineWords));

					} else {
						lines.add(_TextLine.substring(i * lineWords, (i + 1)
								* lineWords));
					}
				}
			}
		}

		return lines;
	}

	@RequestMapping("list.html")
	public String toWriteListPage(HttpServletRequest request, Integer page,
			String bKeywords) {
		int index = 1;
		if (page != null && page > 0) {
			index = page;
		}

		Pagination<EnhancedEBookChapter> pagination = new Pagination<EnhancedEBookChapter>(
				index, 20, true);
		pagination.addOrder(
				new Order(EBookChapter.COLUMN_CREATE_TIME, Order.ORDER_ASC))
				.addOrder(new Order(EBookChapter.COLUMN_SORT, Order.ORDER_ASC));

		EBookChapterQuery eBookChapterQuery = new EBookChapterQuery();
		eBookChapterQuery
				.setStatuses(Arrays
						.asList(new StatusEnumForPublish[] { StatusEnumForPublish.ALREADY_RELEASED }));
		eBookChapterQuery.setLike_title(bKeywords);

		pagination = eBookChapterService.getPagination(eBookChapterQuery,
				pagination, null);
		if (Detect.notEmpty(pagination.getItems())) {
			request.setAttribute("pagination", pagination);
			request.setAttribute("chapters", CommonConvent
					.convent2EBookChapterDatas(pagination.getItems()));
		}

		return "web/write/write_list";
	}

	@RequestMapping("list-part.html")
	public String getWriteListPartPage(HttpServletRequest request,
			Integer page, String bKeywords) {
		int index = 1;
		if (page != null && page > 0) {
			index = page;
		}

		Pagination<EnhancedEBookChapter> pagination = new Pagination<EnhancedEBookChapter>(
				index, 20, true);
		pagination.addOrder(
				new Order(EBookChapter.COLUMN_CREATE_TIME, Order.ORDER_ASC))
				.addOrder(new Order(EBookChapter.COLUMN_SORT, Order.ORDER_ASC));

		EBookChapterQuery eBookChapterQuery = new EBookChapterQuery();
		eBookChapterQuery
				.setStatuses(Arrays
						.asList(new StatusEnumForPublish[] { StatusEnumForPublish.ALREADY_RELEASED }));
		eBookChapterQuery.setLike_title(bKeywords);

		pagination = eBookChapterService.getPagination(eBookChapterQuery,
				pagination, null);
		if (Detect.notEmpty(pagination.getItems())) {
			request.setAttribute("pagination", pagination);
			request.setAttribute("chapters", CommonConvent
					.convent2EBookChapterDatas(pagination.getItems()));
		}

		return "web/write/write_list_part";
	}
}
